namespace NRepository.Core.Query.Interceptors.Factories
{
    using System.Collections.Generic;
    using System.Linq;

    public class FactoryQueryInterceptor : IQueryInterceptor
    {
        public FactoryQueryInterceptor(params IFactoryQuery[] queryFactories)
        {
            QueryFactories = queryFactories;
        }

        public FactoryQueryInterceptor(IEnumerable<IFactoryQuery> queryFactories)
        {
            QueryFactories = queryFactories;
        }

        public IEnumerable<IFactoryQuery> QueryFactories
        {
            get;
            private set;
        }

        public IQueryable<T> Query<T>(
                    IQueryRepository repository,
                    IQueryable<T> query,
                    object additionalQueryData) where T : class
        {
            var factory = QueryFactories.FirstOrDefault(p => p.Type == typeof(T));
            if (factory != null)
            {
                var projectedQuery = factory.Query(repository, additionalQueryData);
                return (IQueryable<T>)projectedQuery;
            }

            return query;
        }
    }
}
